package com.bean;

import com.alibaba.fastjson.JSON;
import com.dto.JsonResult;
import com.dto.User;
import com.entity.UserInfo;
import com.utils.HttpUtils;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Yadasu
 * @version 1.0
 * @date 2020/9/29 0029 19:20
 * @usage
 */
@Component
public class JwtOperation {

    @Value("${jwt.config.secret}")
    private String secret;

    @Value("${jwt.config.expire}")
    private Long expire;

    @Autowired(required = false)
    private HttpServletResponse resp;

    /**
     * 创建JWT 【这个方法仅仅用在简单的Web应用整合案例中】
     *
     * @param id      用户id
     * @param subject 用户名
     * @param roles   用户角色
     * @return 创建的JWT的值
     */
    public String createJwt(String id, String subject, String... roles) {
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setId(id);
        jwtBuilder.setSubject(subject);
        jwtBuilder.setIssuedAt(new Date());
        if (null != expire && !expire.equals(-1L)) {
            jwtBuilder.setExpiration(new Date(System.currentTimeMillis() + expire));
        }
        jwtBuilder.signWith(SignatureAlgorithm.HS256, secret);
        jwtBuilder.claim("roles", roles);
        return jwtBuilder.compact();
    }

    /**
     * 根据传入的User对象创建jwt
     *
     * @param user 符合SpringSecurity认证的User对象
     * @return jwt
     */
    public String creatJwt(User user) {
        JwtBuilder builder = Jwts.builder();
        builder.setId(String.valueOf(user.getId()));
        builder.setSubject(user.getName());
        builder.setIssuedAt(new Date());
        if (null != expire && !expire.equals(-1L)) {
            builder.setExpiration(new Date(System.currentTimeMillis() + expire));
        }
        builder.signWith(SignatureAlgorithm.HS256, secret);
        builder.claim("user", JSON.toJSONString(user));
        return builder.compact();
    }

    /**
     * 解析jwt
     *
     * @param jwt 需要解析的jwt
     * @return 解析结果
     */
    public Claims parseJwt(String jwt) {
        try {
            JwtParser jwtParser = Jwts.parser();
            return jwtParser.setSigningKey(secret).parseClaimsJws(jwt).getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            HttpUtils.writeJson(resp, JsonResult.buildFailure(401, "登录信息已过期"), 401);
        }
        return null;
    }

    /**
     * 从请求头中获取token
     * @param request
     * @return
     */
    public String getToken(HttpServletRequest request) {
        final String requestHeader = request.getHeader("auth-token");
        return requestHeader;
    }
}
